package com.sk.bilibili.model.activity;

import com.sk.api.annotations.Autowired;
import com.sk.bilibili.bean.Dynamic;
import com.sk.bilibili.bean.Search;
import com.sk.bilibili.callBack.RequestCallBack;
import com.sk.bilibili.dto.Page;
import com.sk.bilibili.mapper.DynamicMapper;
import com.sk.bilibili.mapper.FocusMapper;
import com.sk.bilibili.mapper.PraiseMapper;
import com.sk.bilibili.mapper.SearchMapper;
import com.sk.bilibili.model.BaseModel;
import com.sk.bilibili.other.JsonMap;
import com.sk.bilibili.utils.RequestUtils;
import com.sk.bilibili.view.activity.DynamicSearchActivity;

import java.util.List;

public class DynamicSearchModel extends BaseModel<DynamicSearchActivity> {

    @Autowired
    SearchMapper searchMapper;
    @Autowired
    DynamicMapper dynamicMapper;
    @Autowired
    PraiseMapper praiseMapper;
    @Autowired
    FocusMapper focusMapper;
    private int size = 8;
    private String keyword;
    private int page;

    @Override
    public void loadData() {
        RequestUtils.process(searchMapper.getRandom(size),
                searches -> view.loadTipSuccess(searches));
        RequestUtils.process(searchMapper.getHistory(),
                searches -> view.loadHistorySuccess(searches));
    }

    public void clearHistory() {
        RequestUtils.process(searchMapper.deleteAll(),
                unused -> view.clearHistorySuccess());
    }

    public void search(String keyword) {
        this.keyword = keyword;
        page = 1;
        JsonMap map = getJsonMap();
        RequestUtils.process(dynamicMapper.pageSearch(map), dynamicPage -> {
            view.loadSuccess(dynamicPage.getRecords());
            page++;
        });
    }

    private JsonMap getJsonMap() {
        JsonMap map = new JsonMap();
        map.put("keyword", keyword);
        map.put("page", page);
        map.put("size", size);
        return map;
    }

    public void loadMore() {
        JsonMap map = getJsonMap();
        RequestUtils.process(dynamicMapper.pageSearch(map), dynamicPage -> {
            view.loadMoreSuccess(dynamicPage.getRecords());
            page++;
        });
    }

    public void praise(int type, Integer targetId) {
        JsonMap map = new JsonMap();
        map.put("type", type);
        map.put("targetId", targetId);
        RequestUtils.process(praiseMapper.switchPraise(map),
                aBoolean -> view.praiseSuccess());
    }

    public void switchFocus(Integer id) {
        RequestUtils.process(focusMapper.switchFocus(id),
                focus -> view.switchFocusSuccess(focus));
    }

}